from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError


class sb_delivery_picking_list_report(models.AbstractModel):
    _name = 'report.sb_sale.sb_delivery_picking_list_report'
    _description = 'sb_delivery_picking_list_report'

    @api.model
    def _get_report_values(self, docids, data=None):
        docs = self.env['ship.instructions'].browse(docids)
        po_map = {}
        for doc in docs:
            po_lines_map = {}
            if doc.select == 'po':
                lines = doc.unique_line_ids.sorted(key=lambda r: r.po_name or '')
                for line in lines:
                    po_name = line.po_name or 'Undefined'
                    for pkg in line.package_ids:
                        po_lines_map.setdefault(po_name, []).append(pkg)

            else:
                for line in doc.line_ids:
                    for pkg in line.package_ids:
                        po_lines_map.setdefault('all', []).append(pkg)
            po_map[doc.id] = po_lines_map
        return {
            'doc_ids': docids,
            'doc_model': 'ship.instructions',
            'docs': docs,  # 保持原樣
            'po_map': po_map,  # 額外提供 dict
            'data': data,
        }
